﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using PPIDataAccess.General;

namespace PPIDataAccess.Data
{
    public class DHandheld
    {
        public static   DataSet SelectAllIdName(string connectionKey)
        {
            SqlDataAdapter da = null;
            try
            {
                da = new SqlDataAdapter("up_Handheld_SelectAllIdName", DBHelper.GetConnection(connectionKey));
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                throw new Exception("Error executing up_Handheld_SelectAllIdName", ex);
            }
            finally
            {
                if (da != null) da.SelectCommand.Connection.Close();
            }
        }

        public static int Insert(string code, string connectionKey)
        {
            SqlCommand cmd = null;
            SqlTransaction tr = null;
            try
            {
                cmd = new SqlCommand("up_Handheld_Insert", DBHelper.GetConnection(connectionKey));
                tr = cmd.Connection.BeginTransaction();
                cmd.Transaction = tr;

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(DBHelper.CreateNVarCharParameter("@Name",255, ParameterDirection.Input, false, code));
                cmd.Parameters.Add(DBHelper.CreateIntParameter("@HandheldId", ParameterDirection.ReturnValue, false, 0));
                cmd.ExecuteNonQuery();
                tr.Commit();
                return (Int32)cmd.Parameters["@HandheldId"].Value;
            }
            catch (Exception ex)
            {
                if (tr != null)
                    tr.Rollback();
                return 0;
            }
            finally
            {
                if (cmd != null) cmd.Connection.Close();
            }
        }

        public static DataSet Select(int id, string connectionKey)
        {
            SqlDataAdapter da = null;
            try
            {
                da = new SqlDataAdapter("up_Handheld_Select", DBHelper.GetConnection(connectionKey));
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.Add(DBHelper.CreateIntParameter("@HandheldId", ParameterDirection.Input, false, id));
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                throw new Exception("Error executing up_Handheld_Select", ex);
            }
            finally
            {
                if (da != null) da.SelectCommand.Connection.Close();
            }
        }
    }
}
